package retrofit2;

import android.content.Context;

import com.tzpay.tzpay.api.API;
import com.tzpay.tzpay.utils.T;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by chenfeiyue on 16/3/11.
 */
public class Retrofit2Instance {

    private static Retrofit2Instance instance = null;

    private OkHttpClient okHttpClient;

    private Retrofit retrofit;

    //信任全部
    private static X509TrustManager xtm = new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] chain, String authType)
                throws CertificateException {
        }
    };

    private final HostnameVerifier HOSTNAME_VERIFIER = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    private X509TrustManager[] xtmArray = new X509TrustManager[]{xtm};

    private Retrofit2Instance(Context context) {
        initRetrofit(context);
    }

    public static Retrofit2Instance init(Context context) {
        if (instance == null) {
            synchronized (Retrofit2Instance.class) {
                if (instance == null) {
                    instance = new Retrofit2Instance(context);
                }
            }
        }
        return instance;
    }


    private void initRetrofit(Context context) {
        CookiesManager manager = new CookiesManager(context);
        try {
            // Allow all hostnames
            //设置信任所有
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(new KeyManager[0], xtmArray, new SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();


            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(20 * 1000, TimeUnit.MILLISECONDS)
                    .readTimeout(20 * 1000, TimeUnit.MILLISECONDS)
                    .sslSocketFactory(socketFactory)
                    .hostnameVerifier(HOSTNAME_VERIFIER)
                    .cookieJar(manager);

            HttpLoggingInterceptor.Level level = T.isTesting ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE;

            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new MyLogger()).setLevel(level);

            builder.addInterceptor(loggingInterceptor);    // log

            okHttpClient = builder.build();
        } catch (Exception e) {
            e.printStackTrace();
            okHttpClient = new OkHttpClient();
        }


        HttpUrl httpUrl = HttpUrl.parse(API.API_URL);
        retrofit = new Retrofit.Builder()
                .baseUrl(httpUrl)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
//                .addConverterFactory(SimpleXmlConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(okHttpClient)
                .build();
    }

    public OkHttpClient getOkHttpClient() {
        return okHttpClient;
    }

    public void setOkHttpClient(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    public Retrofit getRetrofit() {
        return retrofit;
    }

    public void setRetrofit(Retrofit retrofit) {
        this.retrofit = retrofit;
    }

    public static <T> T create(final Class<T> service) {
        if (null == instance || null == instance.retrofit) {
            throw new IllegalArgumentException("Retrofit2Instance has not init!");
        }
        return instance.retrofit.create(service);
    }

    public static Retrofit createRetrofit(String baseUrl) {
        if (null == instance) {
            throw new IllegalArgumentException("Retrofit2Instance has not init!");
        }
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
//                .addConverterFactory(SimpleXmlConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(instance.okHttpClient)
                .build();
    }


    private class MyLogger implements HttpLoggingInterceptor.Logger {

        @Override
        public void log(String message) {
//            T.e("OKHttp", "------------> " + message);
            System.out.println("OKHTTP ---->" + message);
        }
    }
}
